import React, { useState, useEffect } from 'react';
import { Tabs, Input, Checkbox, Timeline, message, Button, Popconfirm, Empty, Modal } from 'antd';
import styles from './index.less';
import { getFetch, doFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import {
  EditFilled,
  StarOutlined,
  StarFilled,
  DeleteOutlined,
  SyncOutlined,
  CaretDownOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import CUNote from './components';
import CUTags from './components/cutag';
import moment from 'moment';
import ViewFileList from './components/viewfilelist';
import { connect } from 'umi';
import InitForm from '../InitForm';
import { area, classify, user } from '@/services/basic';

const NoteList = ({ data, refresh, currentUser, setDefaultValue, type, setModal }) => {
  const { list, total } = data ?? { list: [], total: 0 };

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      message.destroy();
      if (result.code == 0) {
        refresh?.();
      } else {
        message.error(result.message);
      }
    },
  });

  return (
    <div style={{ marginTop: 12 }}>
      <Timeline>
        {list?.map((it, i) => {
          const ismyattention = it?.is_attention; //是否是自己关注
          const ismycreate = it?.creator_id === currentUser?.id && type !== 'record'; //是否是自己创建
          const iftype = type !== 'record';
          return (
            <Timeline.Item
              key={it?.id}
              color={ismycreate ? '#00CCFF' : '#333333'}
              dot={
                iftype ? (
                  <EditFilled
                    onClick={() => {
                      if (!ismycreate) {
                        return;
                      }
                      setDefaultValue({
                        id: it.id,
                        content: it?.content,
                        filelist: it?.files,
                      });
                    }}
                  />
                ) : (
                  <CaretDownOutlined />
                )
              }
            >
              <div>
                <div className="spread" style={{ marginBottom: '0.5em' }}>
                  <div className="center" style={{ gap: 10 }}>
                    <span style={{ flex: 1 }}>
                      {it?.creator_name} 创建于{' '}
                      {moment(it?.created_at).format('YYYY-MM-DD HH:mm:ss')}
                    </span>
                    {iftype && (
                      <>
                        <Popconfirm
                          title="是否转为服务档案？"
                          placement="bottom"
                          okButtonProps={{
                            loading,
                          }}
                          onConfirm={() => {
                            // /api/company_note/change_service_profile

                            run({
                              url: '/wbn-api/company_note/change_service_profile',
                              params: { id: it?.id },
                              method: 'PUT',
                            });
                          }}
                        >
                          <Button size="small" danger type="text" icon={<SyncOutlined />}>
                            服务档案
                          </Button>
                        </Popconfirm>

                        <Button
                          size="small"
                          type="text"
                          icon={<PlusOutlined />}
                          onClick={() => {
                            setModal((s) => ({
                              ...s,
                              open: true,
                              fields: daily(it?.content),
                              title: '新增日常事项',
                              curitem: it,
                            }));
                          }}
                        >
                          日常事项
                        </Button>

                        <Button
                          size="small"
                          type="link"
                          icon={<PlusOutlined />}
                          onClick={() => {
                            setModal((s) => ({
                              ...s,
                              open: true,
                              fields: paydaily(it?.content),
                              title: '新增收款事项',
                              curitem: it,
                            }));
                          }}
                        >
                          收款事项
                        </Button>
                      </>
                    )}
                  </div>

                  <div className="center">
                    {iftype && (
                      <Button
                        type="text"
                        size="small"
                        icon={
                          ismyattention ? (
                            <StarFilled style={{ color: '#FF9D2F' }} />
                          ) : (
                            <StarOutlined />
                          )
                        }
                        onClick={() => {
                          if (ismyattention) {
                            run({
                              url: '/wbn-api/company_note/take_off_attention_company_note',
                              params: { id: it?.id },
                            });
                          } else {
                            run({
                              url: '/wbn-api/company_note/attention_company_note',
                              params: { id: it?.id },
                            });
                          }
                        }}
                      >
                        {ismyattention ? '取消关注' : '关注'}
                      </Button>
                    )}

                    {ismycreate && (
                      <Popconfirm
                        title="是否删除该记事本"
                        okText="删除"
                        cancelText="取消"
                        placement="bottom"
                        onConfirm={(e) => {
                          run({
                            url: '/wbn-api/company_note/' + it?.id,
                            params: {},
                            method: 'DELETE',
                          });
                        }}
                      >
                        <Button danger size="small" type="text" icon={<DeleteOutlined />}>
                          删除
                        </Button>
                      </Popconfirm>
                    )}
                  </div>
                </div>

                <div
                  style={{
                    whiteSpace: 'pre-wrap',
                    backgroundColor: '#f9f9f9',
                    borderRadius: 8,
                    overflow: 'hidden',
                  }}
                >
                  <div style={{ padding: 12 }}>{it?.content}</div>
                  <div style={{ backgroundColor: '#f0f0f0' }}>
                    <ViewFileList files={it?.files} />
                  </div>
                </div>
              </div>
            </Timeline.Item>
          );
        })}
      </Timeline>
      {list?.length === 0 && (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="请在下方添加记事本..." />
      )}
    </div>
  );
};

const daily = (content) => ({
    area_id: {
      value: null,
      type: 'select',
      title: '区域',
      name: ['area_id'],
      required: true,
      options: {
        database: area,
        params: { is_all: 1 },
      },
    },
    work_type_id: {
      value: null,
      type: 'select',
      title: '办事类型',
      name: ['work_type_id'],
      required: true,
      options: {
        database: (params) => getFetch({ url: '/wbn-api/work_type', params }),
        params: { is_all: 1 },
      },
    },
    work_type_level: {
      value: null,
      type: 'select',
      title: '重要程度',
      name: ['work_type_level'],
      required: true,
      formart: ['type', 'name'],
      options: {
        database: (params) => getFetch({ url: '/wbn-api/work_level', params }),
        params: { is_all: 1 },
      },
    },
    limit_day: {
      value: null,
      type: 'inputnumber',
      title: '办理期限（天）',
      name: ['limit_day'],
      required: true,
    },
    task_describe: {
      value: content,
      type: 'textarea',
      title: '任务描述',
      name: ['task_describe'],
      required: false,
      col: {
        span: 24,
      },
    },
    user_id: {
      value: null,
      type: 'select',
      title: '经办人',
      name: ['user_id'],
      required: true,
      options: {
        database: user,
        params: { is_all: 1, enable: true },
      },
      col: {
        span: 24,
      },
    },
  }),
  paydaily = (content) => ({
    area_id: {
      value: null,
      type: 'select',
      title: '区域',
      name: ['area_id'],
      required: true,

      options: {
        database: area,
        params: { is_all: 1 },
      },
    },
    payment_work_type_id: {
      value: null,
      type: 'select',
      title: '收款类型',
      name: ['payment_work_type_id'],
      required: true,
      options: {
        database: (params) => getFetch({ url: '/wbn-api/payment_work_type', params }),
        params: { is_all: 1 },
      },
    },
    limit_day: {
      value: null,
      type: 'inputnumber',
      title: '办理期限（天）',
      name: ['limit_day'],
      required: true,
    },
    payment_nature: {
      value: null,
      type: 'select',
      title: '收款性质',
      name: ['payment_nature'],
      required: true,
      options: [
        {
          value: 'normal', //normal 正常 delay 逾期
          label: '正常',
        },
        {
          value: 'delay',
          label: '逾期',
        },
      ],
    },
    task_describe: {
      value: content,
      type: 'textarea',
      title: '任务描述',
      name: ['task_describe'],
      required: false,
      col: {
        span: 24,
      },
    },
    user_id: {
      value: null,
      type: 'select',
      title: '经办人',
      name: ['user_id'],
      required: true,
      options: {
        database: user,
        params: { is_all: 1, enable: true },
      },
      col: {
        span: 24,
      },
    },
  });

function Note({ company_id, currentUser }) {
  const [params, setParams] = useState({
    content: null,
    is_my_creator: false,
    is_my_attention: false,
  });

  const { data, refresh } = useRequest(
    async () => {
      let res = await getFetch({
        url: '/wbn-api/company_note',
        params: {
          ...params,
          company_id: company_id,
        },
      });
      return res?.data;
    },
    {
      refreshDeps: [params],
    },
  );

  const profile = useRequest(
    async () => {
      let res = await getFetch({
        url: '/wbn-api/service_profile',
        params: {
          ...params,
          company_id: company_id,
        },
      });
      return res?.data;
    },
    {
      refreshDeps: [params],
    },
  );

  const [defaultValue, setDefaultValue] = useState(null);
  const [activeKey, setactiveKey] = useState('note');

  const [modal, setModal] = useState({
    open: false,
    footer: false,
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      message.destroy();
      if (result.code == 0) {
        message.success('操作成功！');
        setModal((s) => ({
          ...s,
          open: false,
        }));
      } else {
        message.error(result.message);
      }
    },
  });

  function saveData(values) {
    if (modal.title === '新增日常事项') {
      run({
        url: '/wbn-api/daily_work',
        params: { ...values, company_id, company_note_id: modal?.curitem?.id },
      });
    } else if (modal.title === '新增收款事项') {
      run({
        url: '/wbn-api/payment_work',
        params: { ...values, company_id, company_note_id: modal?.curitem?.id },
      });
    }
  }

  return (
    <div className={styles?.notecontainer}>
      <Modal {...modal} width={1000} destroyOnClose>
        <InitForm
          fields={modal?.fields}
          submitData={(values) => {
            saveData(values);
          }}
          onChange={(changedValues, allValues) => {
            //联动操作
          }}
          submitting={loading}
        />
      </Modal>

      <Tabs
        activeKey={activeKey}
        onChange={setactiveKey}
        items={[
          {
            label:
              data?.total && data?.total !== 0 ? (
                <span>
                  记事本 <b style={{ fontSize: 16 }}>{data?.total}</b> 条
                </span>
              ) : (
                '记事本'
              ),
            key: 'note',
            children: (
              <NoteList
                data={data}
                refresh={() => {
                  refresh();
                  profile?.refresh();
                }}
                currentUser={currentUser}
                setDefaultValue={setDefaultValue}
                setModal={setModal}
              />
            ),
          }, // 务必填写 key
          {
            label:
              profile?.data?.total && profile?.data?.total !== 0 ? (
                <span>
                  服务档案 <b style={{ fontSize: 16 }}>{profile?.data?.total}</b> 条
                </span>
              ) : (
                '服务档案'
              ),
            key: 'record',
            children: (
              <NoteList
                data={profile?.data}
                refresh={profile?.refresh}
                type="record"
                currentUser={currentUser}
                setDefaultValue={setDefaultValue}
                setModal={setModal}
              />
            ),
          },
        ]}
        tabBarExtraContent={
          <div className="center" style={{ gap: 30 }}>
            <Input.Search
              placeholder="搜索沟通记录关键词"
              style={{ width: 240 }}
              onSearch={(val) => {
                setParams((s) => ({
                  ...s,
                  content: val,
                }));
              }}
              allowClear
            />
            <Checkbox.Group
              options={[
                {
                  label: '我创建的',
                  value: 'is_my_creator',
                },
                {
                  label: '我关注的',
                  value: 'is_my_attention',
                },
              ]}
              value={Object.keys(params)?.filter((it) => {
                return params[it] === true;
              })}
              onChange={(vals) => {
                setParams((s) => {
                  const obj = {
                    is_my_creator: false,
                    is_my_attention: false,
                  };
                  vals.forEach((it) => {
                    obj[it] = true;
                  });
                  return {
                    ...s,
                    ...obj,
                  };
                });
              }}
            />
          </div>
        }
      />
      {activeKey === 'note' && (
        <CUNote
          company_id={company_id}
          refresh={refresh}
          defaultValue={defaultValue}
          setDefaultValue={setDefaultValue}
        />
      )}
      <CUTags company_id={company_id} />
    </div>
  );
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Note);
